package com.ktjiaoyu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.server.domain.dto.LoginDto;
import com.ktjiaoyu.server.mapper.AdminMapper;
import com.ktjiaoyu.server.domain.pojo.Admin;
import com.ktjiaoyu.server.security.LoginUser;
import com.ktjiaoyu.server.service.AdminService;
import com.ktjiaoyu.server.utils.JwtTokenUtil;
import com.ktjiaoyu.server.utils.RedisCache;
import com.ktjiaoyu.server.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public String login(LoginDto loginDto) {
        UsernamePasswordAuthenticationToken authRequest
                = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());

        Authentication authenticate = authenticationManager.authenticate(authRequest);

        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        // 登录成功 ，创建一个token（身份卡）,jwt
        String token = JwtTokenUtil.createJWT(loginUser.getAdmin().getId().toString());

        // 把登录的用户存到缓存里
        // key的规范，login:id
        redisCache.setCacheObject(RedisCache.KEY_LOGIN_USER_PREFIX+loginUser.getAdmin().getId(),loginUser,Integer.valueOf(JwtTokenUtil.JWT_TTL.intValue()), TimeUnit.SECONDS);

        return token;
    }

    @Override
    public boolean checkCaptcha(String key,String captcha) {
        String text = redisCache.getCacheObject(RedisCache.CAPTCHA_CODE_KEY+key);
        if(captcha.equals(text)){
            return true;
        }
        return false;
    }

    // 分页显示管理员列表, 并按用户名或手机号模糊查询
    @Override
    public IPage<Admin> selectByPage(Page<Admin> page, String query, String sort) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>();
        queryWrapper.like("name", query).or().like("phone", query);
        // 按id字段进行升序或降序排(取决限前端点击id所在列头)
        if (sort.equals("+id")) {
            queryWrapper.orderByAsc("id");
        } else {
            queryWrapper.orderByDesc("id");
        }

        return super.page(page,queryWrapper);
    }


    @Override
    public Admin getUserInfo() {

        LoginUser loginUser= SecurityUtils.getLoginUser();
        Admin admin = new Admin();
        BeanUtils.copyProperties(loginUser.getAdmin(),admin);
        //密码不要传出去了
        admin.setPassword(null);
        return admin;
    }

    @Override
    public void logout() {
        LoginUser loginUser= SecurityUtils.getLoginUser();
        redisCache.deleteObject(RedisCache.KEY_LOGIN_USER_PREFIX+loginUser.getAdmin().getId());
    }

    // 保存操作员新增信息
    @Override
    public boolean saveAdmin(Admin admin) {
        if (adminMapper.insert(admin) > 0) {
            return true;
        }
        return false;
    }
}




